package thread.parral;

/**
 * 1115. 交替打印FooBar
 */
public
//
class FooBar {
    private int n;
    
    public FooBar(int n) {
        this.n = n;
    }
    
    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            while (flag) {
                Thread.yield();
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            flag = true;
        }
    }
    
    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            while (!flag) {
                Thread.yield();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.
            
            printBar.run();
            flag = false;
        }
    }
    
    // private Semaphore s1 = new Semaphore(0);
    // private Semaphore s2 = new Semaphore(0);
    private volatile boolean flag = false;
}